<template>
  <div class="upload-report-step">
    <a-typography-title :heading="4">步骤2: 病历报告上传</a-typography-title>
    
    <div class="step-container">
      <div class="upload-section">
        <div class="section-title">
          <icon-file />
          <span>上传病历报告</span>
        </div>
        
        <a-upload
          :custom-request="handleUpload"
          :file-list="fileList"
          :limit="1"
          accept=".pdf,.doc,.docx,.txt,.jpg,.png,.jpeg,.json"
          @change="handleChange"
        >
          <template #upload-button>
            <div class="upload-area">
              <div class="upload-icon">
                <icon-file-pdf :style="{ fontSize: '48px', color: 'rgb(var(--danger-6))' }" />
              </div>
              <div class="upload-text">
                <p>点击或拖拽文件到此处上传</p>
                <p class="upload-hint">支持上传JSON病历数据或PDF、Word、TXT文档或扫描图片</p>
              </div>
            </div>
          </template>
        </a-upload>
        
        <div class="upload-info">
          <a-alert v-if="fileList.length === 0" type="info">
            请上传患者的病历报告
          </a-alert>
          <a-alert v-else type="success">
            已成功上传病历报告
          </a-alert>
        </div>
      </div>
      
      <div class="result-section">
        <div class="section-title">
          <icon-book />
          <span>病历报告内容</span>
        </div>
        
        <div v-if="fileList.length === 0" class="empty-report">
          <a-empty description="请先上传病历报告" />
        </div>
        
        <div v-else class="report-content">
          <a-tabs>
            <a-tab-pane key="1" title="报告预览">
              <a-skeleton v-if="isLoading" animation />
              <div v-else class="report-preview">
                <a-typography>
                  <a-typography-title :heading="5">患者基本信息</a-typography-title>
                  <a-descriptions :data="patientInfo" layout="horizontal" />
                  
                  <a-typography-title :heading="5">主诉</a-typography-title>
                  <a-typography-paragraph>
                    患者，男，45岁，因"咳嗽、咳痰伴胸闷3周"入院。
                  </a-typography-paragraph>
                  
                  <a-typography-title :heading="5">现病史</a-typography-title>
                  <a-typography-paragraph>
                    患者3周前无明显诱因出现咳嗽、咳白痰，伴胸闷、气促，无发热，无咯血，无胸痛，无盗汗，无明显消瘦。
                    曾在当地诊所治疗（具体用药不详），症状无明显缓解。2天前在当地医院行胸部CT检查提示"双肺多发斑片状、结节状阴影"，为进一步诊治，来我院就诊，门诊以"肺部感染"收入院。
                  </a-typography-paragraph>
                  
                  <a-typography-title :heading="5">既往史</a-typography-title>
                  <a-typography-paragraph>
                    否认高血压、糖尿病、冠心病等慢性病史，否认肝炎、结核等传染病史，否认外伤手术史，否认药物过敏史。
                  </a-typography-paragraph>
                  
                  <a-typography-title :heading="5">体格检查</a-typography-title>
                  <a-typography-paragraph>
                    体温36.5℃，脉搏80次/分，呼吸20次/分，血压125/75mmHg。神志清楚，精神可，全身皮肤粘膜无黄染及出血点，浅表淋巴结未触及肿大。双肺呼吸音粗，可闻及少量湿啰音。心律齐，各瓣膜听诊区未闻及病理性杂音。腹软，无压痛，肝脾未触及。双下肢无水肿。
                  </a-typography-paragraph>
                </a-typography>
              </div>
            </a-tab-pane>
            <a-tab-pane key="2" title="关键信息提取">
              <a-skeleton v-if="isLoading" animation />
              <div v-else class="report-extraction">
                <a-descriptions :data="extractedInfo" layout="vertical" bordered />
              </div>
            </a-tab-pane>
          </a-tabs>
        </div>
        
        <div class="action-buttons">
          <a-space>
            <a-button @click="goToPrevStep">上一步</a-button>
            <a-button type="primary" :disabled="fileList.length === 0" @click="goToNextStep">
              下一步: 生成诊断报告
            </a-button>
          </a-space>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { Message } from '@arco-design/web-vue';
import { IconFile, IconFilePdf } from '@arco-design/web-vue/es/icon';
import IconBook from '@arco-design/web-vue/es/icon/icon-book';

const emit = defineEmits(['next', 'prev', 'save']);

// 文件上传相关
const fileList = ref<any[]>([]);
const isLoading = ref(false);

// 患者信息
const patientInfo = [
  {
    label: '姓名',
    value: '张三'
  },
  {
    label: '性别',
    value: '男'
  },
  {
    label: '年龄',
    value: '45岁'
  },
  {
    label: '住院号',
    value: '2023101501'
  },
  {
    label: '入院日期',
    value: '2023-10-15'
  },
  {
    label: '科室',
    value: '呼吸内科'
  }
];

// 提取的关键信息
const extractedInfo = [
  {
    label: '主要症状',
    value: '咳嗽、咳痰、胸闷、气促'
  },
  {
    label: '症状持续时间',
    value: '3周'
  },
  {
    label: '影像学表现',
    value: '双肺多发斑片状、结节状阴影'
  },
  {
    label: '初步诊断',
    value: '肺部感染'
  },
  {
    label: '体温',
    value: '36.5℃'
  },
  {
    label: '呼吸音',
    value: '双肺呼吸音粗，可闻及少量湿啰音'
  }
];

// 处理文件上传
const handleUpload = (options: any) => {
  const { file, onProgress, onSuccess } = options;
  
  // 初始化进度
  let percent = 0;
  
  // 模拟上传进度
  const timer = setInterval(() => {
    // 增加进度，但确保不超过100
    percent = Math.min(percent + 10, 99);
    onProgress({ percent });
    
    // 当进度达到99%时，模拟完成上传
    if (percent >= 99) {
      clearInterval(timer);
      
      // 模拟上传完成
      setTimeout(() => {
        onProgress({ percent: 100 });
        onSuccess();
        
        // 模拟加载报告内容
        isLoading.value = true;
        setTimeout(() => {
          isLoading.value = false;
        }, 1000);
      }, 300);
    }
  }, 300);
};

const handleChange = (files: any) => {
  fileList.value = files;
};

// 前往上一步
const goToPrevStep = () => {
  emit('prev');
};

// 前往下一步
const goToNextStep = () => {
  if (fileList.value.length === 0) {
    Message.warning('请先上传病历报告');
    return;
  }

  // 提取病历数据，这里假设我们上传的是JSON格式的病历数据
  let electronicRecord = null;
  
  if (fileList.value[0].file.type === 'application/json') {
    // 如果是JSON文件，尝试解析它
    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        electronicRecord = JSON.parse(e.target?.result as string);
        
        // 从JSON更新提取的信息
        if (electronicRecord) {
          extractedInfo.splice(0, extractedInfo.length, ...Object.entries(electronicRecord).map(([key, value]) => ({
            label: key,
            value: typeof value === 'object' ? JSON.stringify(value) : String(value)
          })));
          
          // 更新患者基本信息
          if (electronicRecord.patient_id) patientInfo[3].value = electronicRecord.patient_id;
          if (electronicRecord.name) patientInfo[0].value = electronicRecord.name;
          if (electronicRecord.gender) patientInfo[1].value = electronicRecord.gender;
          if (electronicRecord.age) patientInfo[2].value = `${electronicRecord.age}岁`;
        }
        
        continueSave(electronicRecord);
      } catch (error) {
        console.error('JSON解析失败:', error);
        Message.error('病历文件格式不正确，请上传有效的JSON文件');
      }
    };
    reader.onerror = () => {
      Message.error('读取文件失败，请重试');
    };
    reader.readAsText(fileList.value[0].file);
  } else {
    // 非JSON文件，直接使用模拟数据
    continueSave(null);
  }
};

// 继续保存并前往下一步
const continueSave = (electronicRecord: any = null) => {
  // 保存当前步骤数据
  const saveData = {
    medicalRecord: {
      file: fileList.value[0],
      patientInfo,
      extractedInfo,
      electronicRecord
    }
  };
  
  emit('save', saveData);
  
  // 进入下一步
  emit('next');
};
</script>

<style scoped>
.upload-report-step {
  padding: var(--spacing-md) 0;
}

.step-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: var(--spacing-xl);
}

.section-title {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  font-weight: 600;
  font-size: 16px;
  margin-bottom: var(--spacing-md);
  color: var(--color-text-1);
}

.upload-section, .result-section {
  background-color: var(--color-bg-2);
  border-radius: var(--radius-lg);
  padding: var(--spacing-lg);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: var(--spacing-xl);
  border: 2px dashed var(--color-border-3);
  border-radius: var(--radius-md);
  background-color: var(--color-fill-1);
  transition: all 0.3s;
  cursor: pointer;
  min-height: 200px;
}

.upload-area:hover {
  border-color: rgb(var(--primary-6));
  background-color: rgba(var(--primary-1), 0.3);
}

.upload-icon {
  margin-bottom: var(--spacing-lg);
}

.upload-text {
  text-align: center;
}

.upload-hint {
  color: var(--color-text-3);
  font-size: 12px;
  margin-top: var(--spacing-sm);
}

.upload-info {
  margin-top: var(--spacing-lg);
}

.empty-report {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 300px;
}

.report-content {
  flex: 1;
  min-height: 300px;
  max-height: 500px;
  overflow-y: auto;
}

.report-preview {
  padding: var(--spacing-md);
}

.action-buttons {
  margin-top: var(--spacing-lg);
  display: flex;
  justify-content: flex-end;
}

:deep(.arco-typography-title) {
  margin-top: var(--spacing-lg);
  margin-bottom: var(--spacing-sm);
}

:deep(.arco-typography-paragraph) {
  margin-bottom: var(--spacing-md);
  line-height: 1.8;
}

:deep(.arco-descriptions) {
  margin-bottom: var(--spacing-lg);
}
</style> 